import puppeteer from 'puppeteer';
import fs from 'fs-extra';
import path from 'path';

(async () => {
  // 启动 Puppeteer
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  // 定义需要预渲染的路由
  const routes = ['/'];

  // 确保 dist 目录存在
  const outputDir = path.resolve('dist');
  await fs.ensureDir(outputDir);

  // 启动 Vite 开发服务器的 URL（需要先运行 npm run build）
  const baseUrl = 'http://localhost:5173'; // 默认 preview 端口

  for (const route of routes) {
    const url = `${baseUrl}${route}`;
    console.log(`Rendering: ${url}`);

    // 访问页面并等待渲染完成
    await page.goto(url, { waitUntil: 'networkidle0' });

    // 确保脚本路径正确（调试用）
    const scriptSrc = await page.evaluate(() => {
      const script = document.querySelector('script[type="module"]');
      return script ? script.src : null;
    });
    console.log(`Script src for ${route}: ${scriptSrc}`);

    let content = await page.content();
    // 手动替换脚本路径<script type="module" src="/src/main.js"></script>
    content = content.replace(
      /<script type="module" src="\/src\/main\.js"><\/script>/,
      '<script type="module" src="./js/index.js"></script>'
    );
    const filePath =
      route === '/' ? path.join(outputDir, 'index.html') : path.join(outputDir, route, 'index.html');
    await fs.ensureDir(path.dirname(filePath));
    await fs.writeFile(filePath, content, 'utf-8');
  }

  // 关闭浏览器
  await browser.close();
  console.log('Pre-rendering complete!');
})();